import fs from 'fs';
import path from 'path';
import TurndownService from 'turndown';

const turndownService = new TurndownService();

// 处理单个HTML文件
async function convertFile(inputPath: string, outputPath: string): Promise<void> {
  try {
    const html = fs.readFileSync(inputPath, 'utf8');
    // 替换HTML中的相对路径链接
    const processedHtml = html.replace(/(href|src)="([^"]+\.html)(#[^"]*)?"/g, (match, attr, path, hash) => {
      return `${attr}="${path.replace(/\.html$/i, '.md')}${hash || ''}"`;
    });
    const markdown = turndownService.turndown(processedHtml);
    fs.writeFileSync(outputPath, markdown);
    console.log(`Converted ${inputPath} to ${outputPath}`);
  } catch (err) {
    console.error(`Error converting ${inputPath}:`, err);
  }
}

// 处理目录
async function convertDirectory(inputDir: string, outputDir: string): Promise<void> {
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
    console.log(`Created output directory: ${outputDir}`);
  }

  const items = fs.readdirSync(inputDir);
  
  for (const item of items) {
    const fullPath = path.join(inputDir, item);
    const stat = fs.statSync(fullPath);
    
    if (stat.isDirectory()) {
      console.log(`Processing subdirectory: ${fullPath}`);
      await convertDirectory(fullPath, path.join(outputDir, item));
    } else if (path.extname(fullPath).toLowerCase() === '.html') {
      const outputPath = path.join(outputDir, item.replace(/\.html$/i, '.md'));
      console.log(`Converting HTML to Markdown: ${fullPath} -> ${outputPath}`);
      await convertFile(fullPath, outputPath);
    } else {
      console.log(`Skipping non-HTML file: ${fullPath}`);
    }
  }
}

// 处理文本输入
function convertText(htmlText: string): string {
  return turndownService.turndown(htmlText);
}

// 主函数
async function main() {
  const args = process.argv.slice(2);
  
  if (args.length === 0) {
    console.log('Usage:');
    console.log('  Convert directory: node index.js <inputDir> <outputDir>');
    console.log('  Convert single file: node index.js <inputFile> <outputFile>');
    console.log('  Convert text: node index.js "<html>...</html>"');
    return;
  }
  
  if (args.length === 1) {
    // 文本模式
    console.log(convertText(args[0]));
  } else {
    const inputPath = args[0];
    const outputPath = args[1];
    const stat = fs.statSync(inputPath);
    
    if (stat.isDirectory()) {
      await convertDirectory(inputPath, outputPath);
    } else {
      await convertFile(inputPath, outputPath);
    }
  }
}

main().catch(err => console.error('Error:', err));